

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="若发现文章有误，敬请指教，感谢@[TOC]  参考资料  视频链接 一、运行环境  CentOS7 JDK8 Flume1.9  二、自定义Source 2.1  程序具体实现导入依赖：pom.xml 12345&lt;dependency&gt;    &lt;groupId&gt;org.apache.flume&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;fl">
<meta property="og:type" content="article">
<meta property="og:title" content="Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试">
<meta property="og:url" content="http://example.com/2022/03/21/Flume%20%E7%AC%94%E8%AE%B04%20%E8%87%AA%E5%AE%9A%E4%B9%89Source%20%E4%B8%8E%20%E8%87%AA%E5%AE%9A%E4%B9%89%20Sink%20%E6%A1%88%E4%BE%8B%E4%BB%A5%E5%8F%8A%E6%B5%8B%E8%AF%95/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="若发现文章有误，敬请指教，感谢@[TOC]  参考资料  视频链接 一、运行环境  CentOS7 JDK8 Flume1.9  二、自定义Source 2.1  程序具体实现导入依赖：pom.xml 12345&lt;dependency&gt;    &lt;groupId&gt;org.apache.flume&lt;&#x2F;groupId&gt;    &lt;artifactId&gt;fl">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/72b8e4ecd98c4e98a3e7ed52716f7422.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/867c9410e3ea4f9791c5aa9455cd6074.png">
<meta property="article:published_time" content="2022-03-20T16:30:36.000Z">
<meta property="article:modified_time" content="2022-08-22T15:43:32.961Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Flume">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/72b8e4ecd98c4e98a3e7ed52716f7422.png">
  
  
  
  <title>Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-03-21 00:30" pubdate>
          2022年3月21日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          38 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>若发现文章有误，敬请指教，感谢<br>@[TOC]</p>
</blockquote>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><hr>
<p> <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1wf4y1G7EQ?p=33">视频链接</a></p>
<h1 id="一、运行环境"><a href="#一、运行环境" class="headerlink" title="一、运行环境"></a>一、运行环境</h1><hr>
<ul>
<li>CentOS7</li>
<li>JDK8</li>
<li>Flume1.9</li>
</ul>
<h1 id="二、自定义Source"><a href="#二、自定义Source" class="headerlink" title="二、自定义Source"></a>二、自定义Source</h1><hr>
<h2 id="2-1-程序具体实现"><a href="#2-1-程序具体实现" class="headerlink" title="2.1  程序具体实现"></a>2.1  程序具体实现</h2><p>导入依赖：<code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.flume<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>flume-ng-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.9.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>
<p>编写自定义的source：<code>UniSource.java</code><br>注：必须继承AbstractSource，并实现Configurable和PollableSource接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.flume.source;<br><br><span class="hljs-keyword">import</span> org.apache.flume.Context;<br><span class="hljs-keyword">import</span> org.apache.flume.Event;<br><span class="hljs-keyword">import</span> org.apache.flume.EventDeliveryException;<br><span class="hljs-keyword">import</span> org.apache.flume.PollableSource;<br><span class="hljs-keyword">import</span> org.apache.flume.conf.Configurable;<br><span class="hljs-keyword">import</span> org.apache.flume.event.SimpleEvent;<br><span class="hljs-keyword">import</span> org.apache.flume.source.AbstractSource;<br><br><span class="hljs-keyword">import</span> java.util.HashMap;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Author: Unirithe</span><br><span class="hljs-comment"> * Date: 2022/3/20</span><br><span class="hljs-comment"> **/</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UniSource</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AbstractSource</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Configurable</span>, PollableSource &#123;<br>    <span class="hljs-comment">// 声明数据源source的前后缀</span><br>    <span class="hljs-keyword">private</span> String prefix;<br>    <span class="hljs-keyword">private</span> String subfix;<br>    <span class="hljs-keyword">private</span> Long delay;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">configure</span><span class="hljs-params">(Context context)</span> &#123;<br>        prefix = context.getString(<span class="hljs-string">&quot;pre&quot;</span>, <span class="hljs-string">&quot;pre-&quot;</span>);<br>        subfix = context.getString(<span class="hljs-string">&quot;sub&quot;</span>);<br>        delay = context.getLong(<span class="hljs-string">&quot;delay&quot;</span>, <span class="hljs-number">2000L</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Status <span class="hljs-title function_">process</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> EventDeliveryException &#123;<br><br>        <span class="hljs-comment">// 1. 循环创建事件信息, 传给channel</span><br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) &#123;<br>                <span class="hljs-comment">// 2. 声明事件</span><br>                <span class="hljs-type">Event</span> <span class="hljs-variable">event</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleEvent</span>();<br>                HashMap&lt;String, String&gt; headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;();<br>                event.setHeaders(headers);<br>                event.setBody((prefix + <span class="hljs-string">&quot;uni:&quot;</span> + i + subfix).getBytes());<br>                getChannelProcessor().processEvent(event);<br>            &#125;<br>            Thread.sleep(delay);<br>            <span class="hljs-keyword">return</span> Status.READY;<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            e.printStackTrace();<br>            <span class="hljs-keyword">return</span> Status.BACKOFF;<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">long</span> <span class="hljs-title function_">getBackOffSleepIncrement</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">long</span> <span class="hljs-title function_">getMaxBackOffSleepInterval</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>使用Maven打包成jar包，并发送到节点Flume根目录下的<code>lib</code>文件夹里</p>
<h2 id="2-2-Flume配置"><a href="#2-2-Flume配置" class="headerlink" title="2.2  Flume配置"></a>2.2  Flume配置</h2><p>注：a1.sources.r1.type指定为自定义source类的具体类名即可。</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs ini"><span class="hljs-attr">a1.sources</span> = r1<br><span class="hljs-attr">a1.sinks</span> = k1<br><span class="hljs-attr">a1.channels</span> = c1<br><br><span class="hljs-comment"># 配置自定义的数据源 </span><br><span class="hljs-attr">a1.sources.r1.type</span> = com.uni.flume.source.UniSource<br><span class="hljs-comment"># 消息前缀，默认为pre-</span><br><span class="hljs-attr">a1.sources.r1.pre</span> = hhh-<br><span class="hljs-comment"># 消息后缀，默认为空</span><br><span class="hljs-attr">a1.sources.r1.sub</span> = -hhh<br><span class="hljs-comment"># 消息频率，默认每2000ms5条</span><br><span class="hljs-attr">a1.sources.r1.deley</span> = <span class="hljs-number">1000</span><br><br><span class="hljs-attr">a1.sinks.k1.type</span> = logger<br><br><span class="hljs-attr">a1.channels.c1.type</span> = memory<br><span class="hljs-attr">a1.channels.c1.capacity</span> = <span class="hljs-number">1000</span><br><span class="hljs-attr">a1.channels.c1.transactionCapacity</span> = <span class="hljs-number">100</span><br><br><span class="hljs-attr">a1.sinks.k1.channel</span> = c1<br><span class="hljs-attr">a1.sources.r1.channels</span> = c1<br></code></pre></td></tr></table></figure>
<h2 id="2-3-测试"><a href="#2-3-测试" class="headerlink" title="2.3  测试"></a>2.3  测试</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell"><span class="hljs-meta prompt_">$ </span><span class="language-bash">bin/flume-ng agent -c conf/ -n a1 -f job/custom-source-console.conf -Dflume.root.logger=INFO,console</span><br></code></pre></td></tr></table></figure>
<p>测试结果：<br><img src="https://img-blog.csdnimg.cn/72b8e4ecd98c4e98a3e7ed52716f7422.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="三、自定义Sink"><a href="#三、自定义Sink" class="headerlink" title="三、自定义Sink"></a>三、自定义Sink</h1><hr>
<h2 id="3-1-编写程序"><a href="#3-1-编写程序" class="headerlink" title="3.1  编写程序"></a>3.1  编写程序</h2><p>导入Flume的依赖<code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.flume<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>flume-ng-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.9.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>
<p>自定义Sink类 <code>UniSink.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.flume.sink;<br><br><span class="hljs-keyword">import</span> org.apache.flume.*;<br><span class="hljs-keyword">import</span> org.apache.flume.conf.Configurable;<br><span class="hljs-keyword">import</span> org.apache.flume.sink.AbstractSink;<br><span class="hljs-keyword">import</span> org.slf4j.Logger;<br><span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;<br><br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Author: Unirithe</span><br><span class="hljs-comment"> * Date: 2022/3/21</span><br><span class="hljs-comment"> **/</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UniSink</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AbstractSink</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Configurable</span> &#123;<br>    <span class="hljs-comment">// 声明数据的前后缀</span><br>    <span class="hljs-keyword">private</span> String prefix;<br>    <span class="hljs-keyword">private</span> String subfix;<br><br>    <span class="hljs-comment">// 创建 Logger 对象</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">Logger</span> <span class="hljs-variable">logger</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(UniSink.class);<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">configure</span><span class="hljs-params">(Context context)</span> &#123;<br>        prefix = context.getString(<span class="hljs-string">&quot;pre&quot;</span>, <span class="hljs-string">&quot;pre-&quot;</span>);<br>        subfix = context.getString(<span class="hljs-string">&quot;sub&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Status <span class="hljs-title function_">process</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> EventDeliveryException &#123;<br>        <span class="hljs-comment">// 1. 获取 Channel 并开启事务</span><br>        <span class="hljs-type">Channel</span> <span class="hljs-variable">channel</span> <span class="hljs-operator">=</span> getChannel();<br>        <span class="hljs-type">Transaction</span> <span class="hljs-variable">transaction</span> <span class="hljs-operator">=</span> channel.getTransaction();<br>        transaction.begin();<br>        <span class="hljs-comment">// 2. 从Channel中抓取数据打印到控制台</span><br>        <span class="hljs-keyword">try</span>&#123;<br>            <span class="hljs-comment">// 2.1 抓取数据</span><br>            Event event;<br>            <span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>)&#123;<br>                event = channel.take();<br>                <span class="hljs-keyword">if</span>(event != <span class="hljs-literal">null</span>)<br>                    <span class="hljs-keyword">break</span>;<br>            &#125;<br>            <span class="hljs-comment">// 2.2 处理数据</span><br>            logger.info(prefix + <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(event.getBody()) + subfix);<br>            <span class="hljs-comment">// 2.3 提交事务</span><br>            transaction.commit();<br>            <span class="hljs-keyword">return</span> Status.READY;<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e)&#123;<br>            <span class="hljs-comment">// 回滚</span><br>            transaction.rollback();<br>            <span class="hljs-keyword">return</span> Status.BACKOFF;<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            transaction.close();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>和之前一样，使用Maven打包，发送到节点的Flume根目录下的<code>lib</code>文件夹</p>
<h2 id="3-2-Flume配置"><a href="#3-2-Flume配置" class="headerlink" title="3.2  Flume配置"></a>3.2  Flume配置</h2><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs ini"><span class="hljs-attr">a1.sources</span> = r1<br><span class="hljs-attr">a1.sinks</span> = k1<br><span class="hljs-attr">a1.channels</span> = c1<br><br><span class="hljs-attr">a1.sources.r1.type</span> = netcat<br><span class="hljs-attr">a1.sources.r1.bind</span> = localhost<br><span class="hljs-attr">a1.sources.r1.port</span> = <span class="hljs-number">44444</span><br><br><span class="hljs-comment"># 配置自定义的Sink，给消息添加前后缀</span><br><span class="hljs-attr">a1.sinks.k1.type</span> = com.uni.flume.sink.UniSink<br><span class="hljs-attr">a1.sinks.k1.pre</span> = orz-<br><span class="hljs-attr">a1.sinks.k1.sub</span> = -orz<br><br><span class="hljs-attr">a1.channels.c1.type</span> = memory<br><span class="hljs-attr">a1.channels.c1.capacity</span> = <span class="hljs-number">1000</span><br><span class="hljs-attr">a1.channels.c1.transactionCapacity</span> = <span class="hljs-number">100</span><br><br><span class="hljs-attr">a1.sinks.k1.channel</span> = c1<br><span class="hljs-attr">a1.sources.r1.channels</span> = c1<br></code></pre></td></tr></table></figure>
<h2 id="3-3-测试"><a href="#3-3-测试" class="headerlink" title="3.3  测试"></a>3.3  测试</h2><p>（1）启动Flume</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell"><span class="hljs-meta prompt_">$ </span><span class="language-bash">bin/flume-ng agent -c conf/ -n a1 -f job/netcat-flume-console.conf -Dflume.root.logger=INFO,console</span><br></code></pre></td></tr></table></figure>

<p>（2）使用netcat往本地的44444端口发送消息</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">nc localhost 44444<br></code></pre></td></tr></table></figure>

<p><strong>发送消息：</strong><br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/c0157aa53cb0444892ed2ec801602096.png#">https://img-blog.csdnimg.cn/c0157aa53cb0444892ed2ec801602096.png#</a> &#x3D;60%x)</p>
<p><strong>经过自定义的sink时打印的消息：</strong><br><img src="https://img-blog.csdnimg.cn/867c9410e3ea4f9791c5aa9455cd6074.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>至此，自定义的Source与Sink测试完毕。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/" class="category-chain-item">中间件</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Flume/">#Flume</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试</div>
      <div>http://example.com/2022/03/21/Flume 笔记4 自定义Source 与 自定义 Sink 案例以及测试/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年3月21日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/23/Hive%20%E7%AC%94%E8%AE%B01%20DDL%E6%95%B0%E6%8D%AE%E5%AE%9A%E4%B9%89%E6%93%8D%E4%BD%9C%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4%20_%20%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%95%B0%E6%8D%AE%E5%BA%93%E3%80%81%E6%95%B0%E6%8D%AE%E8%A1%A8%E3%80%81%E5%88%97/" title="Hive 笔记1 DDL数据定义操作常用命令 _ 增删改查数据库、数据表、列">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Hive 笔记1 DDL数据定义操作常用命令 _ 增删改查数据库、数据表、列</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/20/Flume%20%E7%AC%94%E8%AE%B03%20source%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8%E9%80%89%E6%8B%A9%E5%99%A8%20_%20%E7%AE%80%E5%8D%95%E7%9A%84%E6%8B%A6%E6%88%AA%E5%99%A8%E5%AE%9E%E7%8E%B0%20_%20%E4%B8%8D%E5%90%8C%E9%9B%86%E7%BE%A4%E8%8A%82%E7%82%B9%E7%9A%84%E6%95%B0%E6%8D%AE%E5%88%86%E6%B5%81/" title="Flume 笔记3 source多路复用选择器 _ 简单的拦截器实现 _ 不同集群节点的数据分流">
                        <span class="hidden-mobile">Flume 笔记3 source多路复用选择器 _ 简单的拦截器实现 _ 不同集群节点的数据分流</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
